<template>
<h1>发微博页面</h1>
<div style="width: 500px;margin: 0 auto">
  <el-input placeholder="微博正文" v-model="weibo.content"></el-input>
  <el-upload
      v-model:file-list="fileList"
      action="http://localhost:8080/v1/upload"
      name="file"
      limit="9"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
  <el-button type="primary" @click="post">发布</el-button>
</div>
</template>

<script setup>
import {ref} from "vue";
import router from "@/router";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";

import { Plus } from '@element-plus/icons-vue'

const fileList = ref([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  //得到要删除图片的路径
  let imgUrl = uploadFile.response.data;
  axios.post('http://localhost:8080/v1/remove?imgUrl='+imgUrl)
  .then((response)=>{
    if (response.data.code==2001){
      ElMessage.success("服务器文件删除完成!");
    }
  })

}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
      dialogVisible.value = true
}



const weibo = ref({content:''});
const post = ()=>{
  if (fileList.value.length>0){
    let imgUrls = [];
    for (let file of fileList.value) {
      let imgUrl = file.response.data;//得到图片路径
      imgUrls.push(imgUrl);
    }
    weibo.value.imgUrls = imgUrls.toString();
  }

  //得到登录的用户信息
  let user = localStorage.user?JSON.parse(localStorage.user):null;
  if (user==null){
    alert("请先登录!");
    router.push('/login');
    return;
  }
  //给微博对象设置作者id
  weibo.value.userId = user.id;
  //把JS对象转成查询字符串格式
  let data = qs.stringify(weibo.value);
  //发出请求
  axios.post('http://localhost:8080/v1/weibos/add-new',data)
  .then((response)=>{
    if (response.data.code==2001){
      ElMessage.success("发布成功!");
      router.push('/');
    }
  })



}
</script>

<style scoped>

</style>